<template>
  <div :style="{ 'height': wrapperHeight }" v-loading="loading">
    <el-table ref="tableData" :stripe="stripe" :height="height" :max-height="maxHeight"
      :header-cell-style="{ backgroundColor: '#409EFF', color: '#fff' }"
      header-row-class-name="table-list-header" row-class-name="table-list-row" :sum-text="sumText" :size="value" :default-expand-all="defaultExpandAll" :show-summary="showSummary" :summary-method="getSummaries" :cell-style="cellStyle" :cell-class-name="cellClassName" :data="data"
      @selection-change="handleSelectionChange" @current-change="handleTableCurrentChange"
      @row-click="handleTableRowClick" @cell-click="handleTableCellClick" @select="handleSelectChange" @header-dragend="headerDragend" @select-all="selectAll" @expand-change="expandChange" v-bind="otherConfig" :border="true">
      <template v-for="(item, index) in columns">
        <!-- 自定义内容 -->
        <slot v-if="item.expand" :name="item.expand" :fixed="item.fixed" :height="item.height">
        </slot>
        <!-- 选择框 -->
        <el-table-column v-else-if="item.selection" type="selection" width="90" :fixed="item.fixed" align="center"
          header-align="center" :key="`selection_${index}`"></el-table-column>
        <!-- 序号 -->
        <el-table-column v-else-if="item.index" type="index" :width="item.width || '90'" :fixed="item.fixed" label="序号"
          :index="indexMethod" :key="`index_${index}`" align="center"></el-table-column>
        <!-- 多级表头 -->
        <el-table-column v-else-if="item.multi" align="center" :label="item.label" :key="`multi_${index}`">
          <el-table-column v-for="(child, childIndex) in item.children" :key="`child_${index}_${childIndex}`"
            v-bind="child">
          </el-table-column>
        </el-table-column>
        <!-- 自定义内容 -->
        <slot v-else-if="item.slot" show-overflow-tooltip :name="item.slot" :fixed="item.fixed" :height="item.height">
        </slot>
        <!-- 常规字段 -->
        <el-table-column v-else show-overflow-tooltip v-bind="item" :sortable="item.sortable" :fixed="item.fixed" :render-header="item.renderHeader" :formatter="item.formatter" :min-width="item.minWidth"
          :key="`normal_${index}`"></el-table-column>
      </template>
    </el-table>
    <slot name="custom-middle"></slot>
    <!-- eslint-disable -->
    <el-card class="box-card" shadow="never" v-if="isPaginationShow && pagination.total">
      <div>
        <el-pagination v-if="isPaginationShow && pagination.total" class="opagination" :background="pageBackgroud"
          :layout="layout" :small="small" :page-sizes="[10, 20, 30, 50]"
          :current-page.sync="pagination.current" :page-size="pagination.size" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    <!-- eslint-enable -->
    <!-- 自定义内容 -->
    <slot name="custom-content"></slot>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  name: 'mainTable',
  props: {
    small: {
      type: Boolean,
      default: false
    },
    layout: {
      type: String,
      default: 'total, sizes, prev, pager, next, jumper'
    },
    pageBackgroud: {
      type: Boolean,
      default: true
    },
    columns: {
      type: Array,
      default: () => []
    },
    data: {
      type: Array,
      default: () => []
    },
    pagination: {
      type: Object,
      default: () => ({
        current: 1,
        size: 10,
        total: 0
      })
    },
    showSummary: {
      type: Boolean,
      default: false
    },
    isPaginationShow: {
      type: Boolean,
      default: true
    },
    wrapperHeight: {
      type: [Number, String],
      default: '100%' // 一般情况下，更多地是配置父元素的高度，table的高度根据父元素高度计算
    },
    height: {
      type: [Number, String],
      default: 'calc(100% - 48px)' // table的默认高度是 父元素高度 减去 pagination高度，一般情况下，这个默认配置就够用了，有特殊场景可以另配置
    },
    maxHeight: {
      type: [Number, String],
      default: 'auto'
    },
    // tableSize: {
    //   type: String,
    //   default: 'medium'
    // },
    defaultExpandAll: {
      type: Boolean,
      default: false
    },
    sumText: {
      type: String,
      default: '合计'
    },
    stripe: {
      type: Boolean,
      default: true
    },
    otherConfig: {
      type: Object,
      default: () => {}
    },
    cellStyle: {
      type: Function,
      default: () => {}
    },
    cellClassName: {
      type: Function,
      default: () => {}
    },
    loading: {
      type: Boolean,
      default: false
    },
    summaryName: {
      type: String,
      default: ''
    }
  },
  computed: {
    /* ...mapState('d2admin/size', [
      'value'
    ]) */
  },
  data () {
    return { value: 'mini'}
  },
  methods: {
    // 序号自增
    indexMethod (index) {
      return index + 1 + (this.pagination.current - 1) * this.pagination.size
    },
    // 切换页码
    handleCurrentChange (value) {
      this.$emit('getData', { page: value })
    },
    // 切换每页条数
    handleSizeChange (value) {
      // current-page和 page-size都支持 .sync修饰符，用了.sync修饰符，就不需要手动给 this.pagination赋值了
      this.pagination.size = value
      this.$emit('getData', { page_size: value })
    },
    // 切换选择
    handleSelectionChange (val) {
      this.$emit('changeSelection', val)
    },
    handleSelectChange (val, row) {
      this.$emit('handleSelectChange', val, row)
    },
    headerDragend (newWidth, oldWidth, column, event) {
      // this.$refs.tableData.doLayout()
      this.$emit('headerDragend', { newWidth, oldWidth, column, event })
    },
    // 合计
    getSummaries ({ columns, data }) {
      const sums = []
      if (this.sumText === '合计') {
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
          } else {
            if (this.summaryName === column.property) {
              const values = (column.property && data.map(item => Number(item[column.property]))) || []
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr)
                  if (!isNaN(value)) {
                    return prev + curr
                  } else {
                    return prev
                  }
                }, 0)
                sums[index] += '元'
              } else {
                sums[index] = '--'
              }
            } else {
              sums[index] = '--'
            }
          }
        })
      } else if (this.sumText === '老人总数') {
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '老人总数'
          } else {
            if (this.summaryName === column.property) {
              const values = (column.property && data.map(item => Number(item[column.property]))) || []
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr)
                  if (!isNaN(value)) {
                    return prev + curr
                  } else {
                    return prev
                  }
                }, 0)
                sums[index] += '人'
              } else {
                sums[index] = '--'
              }
            } else {
              sums[index] = '--'
            }
          }
        })
      }

      this.$nextTick(() => {
        this.$refs.tableData.doLayout()
      })
      return sums
    },
    // 展开行
    expandChange (row, expandedRows) {
      this.$nextTick(() => {
        this.$refs.tableData.doLayout()
      })
      this.$emit('expandChange', row, expandedRows)
    },
    selectAll (val) {
      this.$emit('selectAll', val)
    },
    // 单选
    handleTableCurrentChange (currentRow) {
      this.$emit('changeCurrent', currentRow)
    },
    // 点击行
    handleTableRowClick (currentRow) {
      this.$emit('rowClick', currentRow)
    },
    handleTableCellClick (row, column) {
      this.$emit('cellClick', { row, column })
    }
  },
  watch: {
    data () {
      // 重新请求数据时 table滚动到顶部
      this.$refs.tableData.doLayout()
      this.$refs.tableData.$refs.bodyWrapper.scrollTop = 0
    }
  }
}
</script>

<style lang="scss" scoped>
 .el-table {
    ::v-deep {
      .hover-row{
        td{
          background-color: #4f699d !important;
        }
      }
      tr:hover>td{
         background-color: #4f699d !important;
      }
      td {
        padding: 10px 0 !important;
        font-size: 16px !important;
        background: #11203f !important;
        .cell {
          font-size: 18px !important;
          color: #fff !important;
        }
      }

      th {
        padding: 12px 0 !important;

        .cell {
          font-size: 16px !important;
          color: #fff !important;
        }
      }

      .red-cell div {
        color: #fff;
        background: #f00;
      }

      .green-cell div {
        color: #fff;
        background: green;
      }

      .blue-cell div {
        color: #fff;
        background: rgb(64, 158, 255);
      }

      .yellow-cell div {
        color: #fff;
        background: #ff8000;
      }

      .red-cell-font div {
        color: red;
      }
      .warning-row {
        background: #efd1b3;
      }
    }
  }
  .el-pagination{
    margin: 0;
  }
</style>
